#include "dialog.h"
#include "ui_dialog.h"
QHostAddress host("192.168.51.107");
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    udp_socket = new QUdpSocket(this);
    timer->setInterval(50);
    timer->setSingleShot(false);
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(OpenSlot()));
    connect(udp_socket,SIGNAL(readyRead()),this,SLOT(ReceiveSlot()));
    connect(timer,SIGNAL(timeout()),this,SLOT(TimeSlot()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(PhotoSlot()));
    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(ShowPrierviousImage()));
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(ShowNextImage()));
    connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(SaveImage()));

}

Dialog::~Dialog()
{
    delete ui;
}
void Dialog::OpenSlot()
{
    timer->start();
    TimeSlot();
}
void Dialog::PhotoSlot()
{
    QByteArray text("get_photo");
    udp_socket->writeDatagram(text,host,7777);
    type = 1;
}

void Dialog::ReceiveSlot()
{
    while (udp_socket->hasPendingDatagrams())
    {
        QByteArray datagram;
        // 动态设置大小为第一个挂起的 udp 数据包的大小
        datagram.resize(udp_socket->pendingDatagramSize());
        // 读取数据
        udp_socket->readDatagram(datagram.data(), datagram.size());
        QImage image;
        if (image.loadFromData(datagram))
        {
            // 成功加载图像后，显示图像
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label->setPixmap(pixmap);
            ui->label->setScaledContents(true);
        }
        if(type == 1)
        {
            images.append(image);
            currentIndex = images.size() -1;
            qDebug() << currentIndex;
            // 成功加载图像后，显示图像
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label_2->setPixmap(pixmap);
            ui->label_2->setScaledContents(true);
            type = 0;
        }
    }


}
void Dialog::TimeSlot()
{
    QByteArray text("get_stream");
    udp_socket->writeDatagram(text,host,7777);
}
void Dialog::ShowPrierviousImage()
{
    if (currentIndex > 0) {
        qDebug() << currentIndex;
        currentIndex--;
        QPixmap pixmap = QPixmap::fromImage(images[currentIndex]);
        ui->label_2->setPixmap(pixmap);
        ui->label_2->setScaledContents(true);
    }
}

void Dialog::ShowNextImage()
{
    if (currentIndex < images.size() - 1) {
        currentIndex++;
        QPixmap pixmap = QPixmap::fromImage(images[currentIndex]);
        ui->label_2->setPixmap(pixmap);
        ui->label_2->setScaledContents(true);
    }
}
void Dialog::SaveImage()
{
    QPixmap pixmap = QPixmap::fromImage(images[currentIndex]);
    QString filePath = "D:\\huaqing\\saved_image.jpg"; // 可修改为你想要保存的文件路径
    if(pixmap.save(filePath)) {
        qDebug() << "D:\\huaqing\\Image saved successfully to " << filePath;
    } else {
        qDebug() << "Failed to save image.";
    }
}
